* Calculate summary stats and create table in Excel

capture program drop sumtable
program define sumtable
    version 14.1

    syntax varlist(numeric fv) [if] [in] [aw fw] using/, /*
        */ [sheet(passthru) replace /*
        */  CASEwise Missing Statistics(str) STATS(str) noTotal]

    loc opts ""
    if "`stats'" != "" {
        loc opts "`opts' stats(`stats')"
    }
    if "`statistics'" != "" {
        loc opts "`opts' statistics(`statistics')"
    }

    fvrevar `varlist', list
    loc varlist = r(varlist)

    tabstat `varlist' `if' `in' [`weight' `exp'], save `opts' /*
        */ `casewise' `missing' `nototal'

    matrix S = r(StatTotal)'
    qui putexcel set "`using'", `sheet' `replace'
    loc cell = 2
    foreach v of varlist `varlist' {
        loc clbl: var label `v'
        qui putexcel A`cell'=("`clbl'")
        loc cell = `cell' + 1
    }
    qui putexcel B1=matrix(S), colnames
    qui putexcel clear
end

